<?php

namespace App\Console\Commands;

use App\Library\Logic\OpenIdLogic;
use App\Library\Logic\ShopProductLogic;
use App\Models\OpenIdModel;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class ProductPlugCommand extends Command
{
    /**
     * 捡漏商品发送降价微信消息
     *
     * @var string
     */
    protected $signature = 'command:plug {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     *
     * @return void
     * @throws GuzzleException
     *
     */
    public function handle(): void
    {
        return;
        $serialNumber = $this->argument('serialNumber');
        $product = ShopProductLogic::findByWhere(['serialNumber' => $serialNumber]);
        if (is_null($product) || (int)$product->product_status === 1) return;
        else if ((int)$product->product_stock_empty !== 1) return;
        $openid = OpenIdModel::query()
            ->leftJoin('shop_user_collect', 'shop_user_collect.user_id', 'open_id.user_id')
            ->where([
                'uc_source_id' => $product->product_id,
                'uc_type' => 1,
                'plateform' => 2,
                'type' => 'wx',
                'is_follow' => 1
            ])->get();
        if (is_null($openid)) return;
        foreach ($openid as $v) {
            self::httpPostData(self::plugPush($product, $v->openid));
        }
    }

    private static function plugPush(Model $product, string $openId): array
    {
        return [
            'touser' => $openId,
            'template_id' => 'ZrzoZgIV_6tLmHmAcT4q2sRNsxFBJzbBNV9QCL4bL2c',
            "miniprogram" => [
                "appid" => __('wechat.miniapp.appId'),
                "pagepath" => "/pagesB/productDetail/index?id=" . $product->product_id
            ],
            'data' => [
                'thing23' => ['value' => mb_substr($product->product_name, 0, 20)],
                'thing9' => ['value' => '降价啦!!!'],
            ]
        ];
    }

    /**
     *
     * @param $data
     * @return void
     * @throws GuzzleException
     *
     */
    static private function httpPostData($data): void
    {
        $url = sprintf(__('wechat.wx.url.step4'), wechatAccessToken('mp'));
        $client = new Client();
        $response = $client->post($url, ['json' => $data])->getBody()->getContents();
        $result = json_decode($response, true);
        Log::debug('plug:' . var_export($result, true));
    }
}
